package test;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.swing.JOptionPane;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import rs232Test.Util;

import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.DisposeEvent;

public class Device {

	protected Shell shell;
	OutputStream out = null;
	SerialPort serialPort = null;
	private Combo combo;
	private Combo combo_1;
	private Combo combo_2;
	private Combo combo_3;
	private Combo combo_3_1;
	private Button btnNewButton;
	/**
	 * 心跳线程
	 */
	private Thread heartThread;
	/**
	 * 串口输入流线程
	 */
	private Thread isThread;
	/**
	 * 串口输入流
	 */
	private InputStream is;
	private Text text;
	private Label lblNewLabel_2;
	private Display display;
	private Button btnNewButton_2;
	private Label lblNewLabel_3;
	private Text text_1;
	private Button btnCheckButton;
	private Button btnCheckButton_1;
	private Button btnCheckButton_2;
	private Button btnCheckButton_3;
	private Button btnCheckButton_4;
	private Button btnCheckButton_5;
	private Button btnCheckButton_6;
	private Button btnCheckButton_7;
	private Button btnCheckButton_8;
	private Button btnCheckButton_9;
	private Button btnCheckButton_10;
	private Text text_2;
	private Label lblNewLabel_4;
	private Label lblNewLabel_5;
	private Text text_3;
	

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Device window = new Device();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	private void close() {
		try {
			if(isThread!=null) {
				if(isThread.isAlive()) {
					isThread.interrupt();	
					isThread=null;
				}
			}
			if(heartThread!=null) {
				if(heartThread.isAlive()) {
					heartThread.interrupt();	
					heartThread=null;
				}
			}
			if(out!=null) {
				out.close();
				out=null;
			}
			if(serialPort!=null) {
				serialPort.close();
				serialPort=null;
			}
			btnNewButton.setEnabled(true);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				close();
			}
		});
		shell.setSize(600, 593);
		shell.setText("设备端");
		
		btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				connect();
			}
		});
		btnNewButton.setBounds(10, 10, 80, 27);
		btnNewButton.setText("连接");
		
		Button btnNewButton_1 = new Button(shell, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				close();
			}
		});
		btnNewButton_1.setText("断开");
		btnNewButton_1.setBounds(96, 10, 80, 27);
		
		text = new Text(shell, SWT.BORDER |  SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		text.setBounds(10, 64, 252, 144);
		
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(10, 399, 48, 17);
		lblNewLabel.setText("串   口：");
		
		Label lblNewLabel_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1.setText("波特率：");
		lblNewLabel_1.setBounds(10, 430, 48, 17);
		
		Label lblNewLabel_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1.setText("校验位：");
		lblNewLabel_1_1.setBounds(10, 461, 48, 17);
		
		Label lblNewLabel_1_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1_1.setText("数据位：");
		lblNewLabel_1_1_1.setBounds(10, 491, 48, 17);
		
		Label lblNewLabel_1_1_1_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1_1_1_1.setText("停止位：");
		lblNewLabel_1_1_1_1.setBounds(10, 522, 48, 17);
		
		combo = new Combo(shell, SWT.NONE);
		combo.setItems(new String[] {"COM1", "COM2", "COM3", "COM4"});
		combo.setToolTipText("");
		combo.setBounds(64, 396, 88, 25);
		combo.setText("COM2");
		
		combo_1 = new Combo(shell, SWT.NONE);
		combo_1.setItems(new String[] {"300", "600", "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "57600", "115200"});
		combo_1.setBounds(64, 427, 88, 25);
		combo_1.setText("9600");
		
		combo_2 = new Combo(shell, SWT.NONE);
		combo_2.setItems(new String[] {"NONE", "ODD", "EVEN"});
		combo_2.setBounds(64, 458, 88, 25);
		combo_2.setText("NONE");
		
		combo_3 = new Combo(shell, SWT.NONE);
		combo_3.setItems(new String[] {"6", "7", "8"});
		combo_3.setBounds(64, 488, 88, 25);
		combo_3.setText("8");
		
		combo_3_1 = new Combo(shell, SWT.NONE);
		combo_3_1.setItems(new String[] {"1", "2"});
		combo_3_1.setBounds(64, 519, 88, 25);
		combo_3_1.setText("1");
		
		lblNewLabel_2 = new Label(shell, SWT.NONE);
		lblNewLabel_2.setText("接收的数据：");
		lblNewLabel_2.setBounds(10, 43, 80, 17);
		
		btnNewButton_2 = new Button(shell, SWT.NONE);
		btnNewButton_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.setText("");
				text_3.setText("");
			}
		});
		btnNewButton_2.setText("清空");
		btnNewButton_2.setBounds(182, 10, 80, 27);
		
		lblNewLabel_3 = new Label(shell, SWT.NONE);
		lblNewLabel_3.setText("当前温度：");
		lblNewLabel_3.setBounds(268, 13, 60, 17);
		
		text_1 = new Text(shell, SWT.BORDER);
		text_1.setEnabled(false);
		text_1.setBounds(334, 10, 73, 23);
		
		btnCheckButton = new Button(shell, SWT.CHECK);
		btnCheckButton.setText("抽屉1");
		btnCheckButton.setBounds(268, 67, 60, 17);
		
		btnCheckButton_1 = new Button(shell, SWT.CHECK);
		btnCheckButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
			}
		});
		btnCheckButton_1.setText("抽屉2");
		btnCheckButton_1.setBounds(268, 87, 60, 17);
		
		btnCheckButton_2 = new Button(shell, SWT.CHECK);
		btnCheckButton_2.setText("抽屉3");
		btnCheckButton_2.setBounds(268, 110, 60, 17);
		
		btnCheckButton_3 = new Button(shell, SWT.CHECK);
		btnCheckButton_3.setText("抽屉4");
		btnCheckButton_3.setBounds(268, 133, 60, 17);
		
		btnCheckButton_4 = new Button(shell, SWT.CHECK);
		btnCheckButton_4.setText("抽屉5");
		btnCheckButton_4.setBounds(268, 156, 60, 17);
		
		btnCheckButton_5 = new Button(shell, SWT.CHECK);
		btnCheckButton_5.setText("抽屉6");
		btnCheckButton_5.setBounds(268, 179, 60, 17);
		
		btnCheckButton_6 = new Button(shell, SWT.CHECK);
		btnCheckButton_6.setText("抽屉7");
		btnCheckButton_6.setBounds(268, 202, 60, 17);
		
		btnCheckButton_7 = new Button(shell, SWT.CHECK);
		btnCheckButton_7.setText("抽屉8");
		btnCheckButton_7.setBounds(268, 225, 60, 17);
		
		btnCheckButton_8 = new Button(shell, SWT.CHECK);
		btnCheckButton_8.setText("抽屉9");
		btnCheckButton_8.setBounds(268, 248, 60, 17);
		
		btnCheckButton_9 = new Button(shell, SWT.CHECK);
		btnCheckButton_9.setText("抽屉10");
		btnCheckButton_9.setBounds(268, 271, 60, 17);
		
		btnCheckButton_10 = new Button(shell, SWT.CHECK);
		btnCheckButton_10.setText("压缩机");
		btnCheckButton_10.setBounds(268, 362, 60, 17);
		
		text_2 = new Text(shell, SWT.BORDER);
		text_2.setEnabled(false);
		text_2.setBounds(491, 10, 73, 23);
		
		lblNewLabel_4 = new Label(shell, SWT.NONE);
		lblNewLabel_4.setText("设置的温度：");
		lblNewLabel_4.setBounds(413, 13, 73, 17);
		
		lblNewLabel_5 = new Label(shell, SWT.NONE);
		lblNewLabel_5.setText("发送的数据：");
		lblNewLabel_5.setBounds(10, 214, 80, 17);
		
		text_3 = new Text(shell, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		text_3.setBounds(10, 235, 252, 144);

	}
	
	/**
	 * 输出数据
	 * @param data
	 */
	public void outData(byte[] data) {
		display.asyncExec(new Runnable() {
			@Override
			public void run() {
				try {
					text_2.setText(text_2.getText()+Util.bytesToHexString(data));
					out.write(data);
					out.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 上传状态
	 * 
	 * FF FF 2C 00 00 10 
	 * 10 01 00 00 01 01 05 01 1E 07 08 08 02 FF 03 FF 03 20 
	 * 10 01 00 00 01 00 00 00 08 3C FF FF 00 00 00 00 
	 * 1C EB FF F7
	 * 
	 */
	public void uploadStatus() {
		byte[] uploadData= {(byte)0xFF,(byte)0xFF,(byte)0x2C,(byte)0x00,(byte)0x00,(byte)0x10,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0xFF,(byte)0xF7};
		byte[] lockStatus=getLockStatus();
		uploadData[18]=lockStatus[0];//锁状态高位
		uploadData[19]=lockStatus[1];//锁状态地位
	}
	
	public byte[] getLockStatus() {
		byte[] result=new byte[2];
		
		//btnCheckButton.get
		
		
		return result;
	}
	
	
	public void connect() {
		try {
			 //通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(combo.getText());
            //打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(combo.getText(), 2000);
            //判断是不是串口
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                //设置一下串口的波特率等参数 baudrate 
                //serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                int PARITY=SerialPort.PARITY_NONE;
                if(combo_2.getText().equals("NONE")) {
                	PARITY=SerialPort.PARITY_NONE;
                }
                if(combo_2.getText().equals("ODD")) {
                	PARITY=SerialPort.PARITY_ODD;
                }
                if(combo_2.getText().equals("EVEN")) {
                	PARITY=SerialPort.PARITY_EVEN;
                }
                serialPort.setSerialPortParams(Integer.parseInt(combo_1.getText()), Integer.parseInt(combo_3.getText()), Integer.parseInt(combo_3_1.getText()),PARITY);
                
            }
            out = serialPort.getOutputStream();
            
            is = serialPort.getInputStream();
            
            isThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while(true) {
							if(Thread.currentThread().isInterrupted()) {
								break;
							}else {
								try {
									int availableBytes=is.available();
									byte[] cache = new byte[availableBytes];
									if (availableBytes > 0) {
										is.read(cache);
										String dataHex=Util.bytesToHexString(cache);
										if(dataHex.length()>4) {
											if(dataHex.substring(0, 4).equals("FFFF")) {//消息头
												if(dataHex.substring(dataHex.length()-4, dataHex.length()).equals("FFF7")) {//消息尾
													display.asyncExec(new Runnable() {
														@Override
														public void run() {
															text.setText(text.getText()+dataHex+"\n");
														}
													});
													
													String functionNum=Util.bytesToHexString(Util.getBit(cache, 5,1));//功能号
													if(functionNum.equals("01")) {
														uploadStatus();
													}
													
												}
											}
										}
									}
								} catch (ArrayIndexOutOfBoundsException e) {
									continue;
								}
							}
						}
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
            isThread.start();
            
            /*
            heartThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while(true) {
							if(Thread.currentThread().isInterrupted()) {
								break;
							}else {
								String time=String.valueOf(new Date().getTime());
								System.out.println(time);
								
								display.asyncExec(new Runnable() {
									@Override
									public void run() {
										text.setText(text.getText()+time);
									}
								});
								
								out.write(time.getBytes());
								out.flush();
							}
							Thread.sleep(1000);
			            }	
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
            heartThread.start();
            */
            
            btnNewButton.setEnabled(false);
           
		} catch (Exception e) {
			MessageBox msg=new MessageBox(shell);
			msg.setText("提示");
			msg.setMessage("连接失败！");
			msg.open();
			e.printStackTrace();
		} 
	}
}
